package com.qf.service.impl;

import com.qf.config.IdWorker;
import com.qf.constant.CacheConstants;
import com.qf.constant.RabbitMQConstants;
import com.qf.constant.ReportStateConstants;
import com.qf.constant.SourceType;
import com.qf.fegin.CacheFegin;
import com.qf.form.SmsInterfaceForm;
import com.qf.model.StandardSubmit;
import com.qf.service.InterfaceService;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @author dell
 * @version V1.0
 * @Date 2022/6/2 14:49:14
 */
@Service
public class InterfaceServiceImpl implements InterfaceService {

    @Resource
    private CacheFegin cacheFegin;

    @Autowired
    private IdWorker idWorker;

    @Autowired
    private RabbitTemplate rabbitTemplate;


    @Override
    public Map check(SmsInterfaceForm smsInterfaceForm) {

        Map result = new HashMap<String,Object>();

        String clientID = smsInterfaceForm.getClientID();

        //客户的所以信息
        Map<String,String> map = cacheFegin.hMGet(CacheConstants.CACHE_PREFIX_CLIENT + clientID);

        if (map == null && map.size() == 0){
            result.put("code", "101");
            result.put("msg", "认证错误：客户id 错误");
            return result;
        }

        if (StringUtils.isEmpty(smsInterfaceForm.getPwd()) ||!smsInterfaceForm.getPwd().equals(map.get("pwd"))){
            result.put("code", "102");
            result.put("msg", "认证错误：密码 错误");
            return result;
        }

        String ipaddress = map.get("ipaddress");
        for (String ip : ipaddress.split(",")) {
            if (!StringUtils.isEmpty(smsInterfaceForm.getIp())&&smsInterfaceForm.getIp().equals(ip)){
                break;
            }else {
                result.put("code", "103");
                result.put("msg", "认证错误：IP 错误");
                return result;
            }
        }

        if (StringUtils.isEmpty(smsInterfaceForm.getContent() )|| smsInterfaceForm.getContent().length() > 500){
            result.put("code", "104");
            result.put("msg", "认证错误：消息长度错，为空或超长（目前定为500个字）");
            return result;
        }

        // 手机号合法性
        String mobile = smsInterfaceForm.getMobile();
        String[] mobileArray = mobile.split(",");

        if (null != mobileArray && mobileArray.length > 100){
            result.put("code", "105");
            result.put("msg", "认证错误：手机号太多了 ");
            return result;
        }

        String regex = "^[1](([3|5|8][\\d])|([4][4,5,6,7,8,9])|([6][2,5,6,7])|([7][^9])|([9][1,8,9]))[\\d]{8}$";
        for (String m : mobileArray) {
            if (!m.matches(regex)) {
                result.put("code", "105");
                result.put("msg", "认证错误：手机号 错误");
                return result;
            }
        }


        result.put("code", "0");
        result.put("msg", "接收成功");


        //为了解决高并发  大量短信  发送rabbitMQ 进行削峰
        for (String s : mobileArray) {
            StandardSubmit standardSubmit = new StandardSubmit();
            //当前唯一id
            standardSubmit.setSequenceId(String.valueOf(idWorker.nextId()));
            //优先级
            standardSubmit.setMessagePriority(Short.parseShort((String)map.get("priority")));
            //客户端 唯一序列
            standardSubmit.setSrcSequenceId(Long.valueOf(smsInterfaceForm.getSrcID()));

            standardSubmit.setClientID(Integer.valueOf(clientID));

            //手机号
            standardSubmit.setDestMobile(s);
            //短信内容
            standardSubmit.setMessageContent(smsInterfaceForm.getContent());
            //手机接收的状态    等待
            standardSubmit.setReportState(ReportStateConstants.WAIT);
            // 短信发送的时间
            standardSubmit.setSendTime(new Date());
            //  发送方式  HTTP 发送
            standardSubmit.setSource(SourceType.HTTP);
            //  发送消息  rabbitMQ的服务端
            rabbitTemplate.convertAndSend(RabbitMQConstants.TOPIC_PRE_SEND + "_exchange"
                    , "routingKey", standardSubmit);
        }

        return result;
    }
}
